<template>
  <div class="crmp-header">
    <div class="logo">
      <img :src="logo_url" alt="" />
    </div>
    <div class="breadcrumb">
      <div class="left">
        <i class="el-icon-s-home"></i>
        <Breadcrumb />
      </div>
      <!-- <div class="orgStyle">
        <el-select v-model="userOrg" placeholder="请选择" @change="changeOrg">
          <el-option v-for="item in orgnizations" :key="item.pid" :label="item.orgName" :value="item.pid"> </el-option>
        </el-select>
      </div> -->
      <div class="right">
        <!-- <el-popover v-model="visibleTo" trigger="hover" popper-class="header-popper" placement="bottom-end">
          <ul class="to-pop">
            <li v-for="(item, index) in toArr" :key="index" @click=";(dialogAdd = true), (objApi = item.objApi)">
              <img :src="require(`@/assets/images/icon/${item.pidUrl}.svg`)" alt="" />
              <span style="margin-top: 5px">{{ item.name }}</span>
            </li>
          </ul>
          <span slot="reference" class="to-style">快捷入口</span>
        </el-popover> -->
        <i class="el-icon-arrow-left" @click="$router.go(-1)"></i>
        <i class="el-icon-refresh-left" @click="$router.go(0)"></i>
        <!-- <i class="el-icon-search" @click="isVisibleSearchCus = true"></i>
        <el-popover v-model="visibleOrg" trigger="hover" popper-class="header-popper">
          <div class="login-pop">
            <span
              v-for="item in orgnizations"
              :key="item.pid"
              :class="{ active: userOrg === item.pid }"
              class="org-btn"
              type="primary"
              size="mini"
            >
              {{ item.orgName }}
            </span>
          </div>
          <i slot="reference" class="el-icon-office-building" style="background-color: #fff; color: #4584fc"></i>
        </el-popover> -->
        <el-badge :max="99" :hidden="messageNum === 0" :value="messageNum" class="message-badge">
          <i class="el-icon-message-solid" @click="messageVisible = true"></i>
        </el-badge>
        <el-avatar fit="contain" :icon="avatorURL ? '' : 'el-icon-user-solid'" :src="avatorURL" />
        <el-popover v-model="visible" trigger="hover" popper-class="header-popper">
          <div class="login-pop">
            <el-button type="primary" size="mini" @click="changeDataDialog = true">修改资料</el-button>
            <el-button type="primary" size="mini" @click="openPsdDialog">修改密码</el-button>
            <el-button type="primary" size="mini" @click="onLogout()">退出系统</el-button>
          </div>
          <span slot="reference" style="color: #fff">{{ userInfo.realName }}</span>
        </el-popover>
      </div>
    </div>

    <!-- 修改资料 -->
    <EditUserInfo v-if="changeDataDialog" :dialog="changeDataDialog" @closeChangeDialog="closeChangeDialog" />

    <!-- 修改密码 -->
    <el-dialog
      width="40%"
      center
      :visible.sync="changePsdDialog"
      :before-close="closePsdDialog"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @open="psdOpen"
    >
      <p slot="title" class="dialog-title">修改密码</p>
      <el-form ref="ruleForm" class="psd-form" :model="ruleForm" :rules="rules" label-width="100px">
        <el-form-item label="原密码" prop="originalPassword">
          <el-input v-model="ruleForm.originalPassword" type="password" placeholder="原登录密码"></el-input>
          <span class="psd-txt">请输入原密码</span>
        </el-form-item>
        <el-form-item label="密码" prop="newPassword">
          <el-input
            v-model="ruleForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            autocomplete="off"
          ></el-input>
          <span class="psd-txt">{{ str }}</span>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input
            v-model="ruleForm.checkPass"
            type="password"
            placeholder="请再次输入密码"
            autocomplete="off"
          ></el-input>
          <span class="psd-txt">确认密码必须和上面密码一致</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="resetForm">重置</el-button> -->
        <el-button class="emty-btn" @click="changePsdDialog = false">取消</el-button>
        <el-button class="btn-style" @click="submitPassWord">确认修改</el-button>
      </span>
    </el-dialog>

    <!-- 删除商机 -->
    <Confirm
      txt="修改成功后须重新登录"
      :confirm-dialog="sucPwdDialog"
      :close-show-btn="false"
      :show-close="false"
      @closeConfirm="sucPwdDialog = false"
      @onConfirm="confirmPwd"
    />

    <!-- 消息提醒 -->
    <!-- <MyDrawer
      @flagTrue="needPowerFlag = true"
      @flagFalse="needPowerFlag = false" :drawer-show="messageVisible" :size="30" @handleClose="handleClose">
      <Message />
    </MyDrawer> -->

    <!-- 消息提醒（为了避免抽屉组件加细滚动条出问题） -->
    <el-drawer
      custom-class="message-drawer"
      :append-to-body="true"
      :modal-append-to-body="true"
      :destroy-on-close="true"
      :visible.sync="messageVisible"
      :before-close="handleClose"
      :show-close="false"
    >
      <Message />
    </el-drawer>

    <!-- 快捷入口 start -->
    <!-- 添加线索 -->
    <ClueListAdd
      v-if="dialogAdd && objApi === 'b_leads'"
      :dialog-add="dialogAdd"
      :sort-type="0"
      @closeDialog="dialogAdd = false"
      @getData="dialogAdd = false"
    />
    <!-- 添加客户 -->
    <CustomerListAdd
      v-if="dialogAdd && objApi === 'b_customer'"
      :dialog-add="dialogAdd"
      @closeDialog="dialogAdd = false"
      @getData="dialogAdd = false"
    >
    </CustomerListAdd>
    <!-- 添加联系人 -->
    <PersonAdd
      v-if="dialogAdd && objApi === 'b_person_contact'"
      :dialog-add="dialogAdd"
      @closeDialog="dialogAdd = false"
      @getData="dialogAdd = false"
    >
    </PersonAdd>
    <!-- 添加商机 -->
    <AddOpp
      v-if="dialogAdd && objApi === 'b_business'"
      :dialog-add="dialogAdd"
      @closeDialog="dialogAdd = false"
      @getData="dialogAdd = false"
    />
    <!-- 添加产品 -->
    <AddProduct
      v-if="dialogAdd && objApi === 'b_product'"
      :dialog-add="dialogAdd"
      @closeDialog="dialogAdd = false"
      @getData="dialogAdd = false"
    />
    <!-- 新增报价 -->
    <AddEditOffer v-if="dialogAdd && objApi === 'b_offer_record'" :visible.sync="dialogAdd" />
    <!-- 添加合同 -->
    <AddContract
      v-if="dialogAdd && objApi === 'b_contract_info'"
      :dialog-add="dialogAdd"
      @closeDialog="dialogAdd = false"
      @getData="dialogAdd = false"
    />
    <!-- 申请开票 -->
    <InvoiceAddEdit
      v-if="dialogAdd && objApi === 'b_invoice_info'"
      :visible.sync="dialogAdd"
      :add-type="1"
      @closeDialog="dialogAdd = false"
    />
    <!-- 办公申请 -->
    <OfficeApplication
      v-if="dialogAdd && objApi === 'c_approve_obj_data'"
      :dialog-add="dialogAdd"
      @closeDialog="dialogAdd = false"
      @getData="dialogAdd = false"
    >
    </OfficeApplication>
    <!-- 快捷入口 end -->

    <!-- 客户查重 -->
    <SearchCustomer :visible.sync="isVisibleSearchCus" />
  </div>
</template>

<script src="https://lf-cdn.coze.cn/obj/unpkg/flow-platform/chat-app-sdk/1.1.0-beta.0/libs/cn/index.js"></script>
<script>
import { setLogout } from '@/network/api/login'
import {
  updatePassword_api,
  getUserInfo,
  queryFiles_api,
  queryUserSecurity_api,
  getLogoInfo_api,
  getQueryUserSecurity,
  getOrgnizationList,
  getObtainCozeTokenApi
} from '@/network/api/user'
import { unreadSum } from '@/network/api/message'
import watermark from '@/utils/watermark.js'

import Breadcrumb from './header/Breadcrumb.vue'
import Message from './header/Message.vue'
import EditUserInfo from './header/EditUserInfo.vue'
import SearchCustomer from './header/SearchCustomer.vue'
import Confirm from '../../views/components/Confirm.vue'

// 快捷入口
import ClueListAdd from '@/views/clueManagement/clueList/ClueListAdd.vue'
import CustomerListAdd from '@/views/customerManagement/customerList/CustomerListAdd.vue'
import PersonAdd from '@/views/customerManagement/customerContactPerson/PersonAdd.vue'
import AddOpp from '@/views/opportunityManagement/oppList/AddOpp.vue'
import AddProduct from '@/views/productManagement/productList/AddProduct.vue'
import AddEditOffer from '@/views/offer/offerList/AddEditOffer.vue'
import AddContract from '@/views/financialManagement/contractList/AddContract.vue'
import InvoiceAddEdit from '@/views/financialManagement/invoice/AddEdit.vue'
import OfficeApplication from '@/views/approvalManagement/List/OfficeApplication.vue'

export default {
  name: 'Header',
  components: {
    Breadcrumb,
    Message,
    EditUserInfo,
    Confirm,
    SearchCustomer,
    ClueListAdd,
    CustomerListAdd,
    PersonAdd,
    AddOpp,
    AddProduct,
    AddEditOffer,
    AddContract,
    InvoiceAddEdit,
    OfficeApplication
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    const validPassword = (rule, value, callback) => {
      // const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{4,20}$/
      // if (!reg.test(value)) {
      //   callback(new Error('密码必须是由4-20位字母和数字组合'))
      // } else
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.newPassword) {
        callback(new Error('确认密码必须和上面密码一致!'))
      } else {
        callback()
      }
    }
    return {
      needPowerFlag: false,
      visible: false,
      visibleOrg: false,
      sucPwdDialog: false,
      changeDataDialog: false,
      changePsdDialog: false,
      messageVisible: false,
      ruleForm: {
        originalPassword: '',
        newPassword: '',
        checkPass: ''
      },
      rules: {
        originalPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
        newPassword: [{ required: true, validator: validatePass, trigger: 'blur' }],
        checkPass: [{ required: true, validator: validPassword, trigger: 'blur' }]
      },
      avatorURL: '',
      str: '',
      userInfo: {},
      orgnizations: [],
      userOrg: '',
      userSecurity: {},
      messageNum: '',
      logo_url: '',
      // 快捷入口
      objApi: '',
      visibleTo: false,
      dialogAdd: false,
      toArr: [
        { name: '客户', pidUrl: '01kehu', objApi: 'b_customer' },
        { name: '联系人', pidUrl: '02lianxiren', objApi: 'b_person_contact' },
        { name: '商机', pidUrl: '03shangji', objApi: 'b_business' },
        { name: '报价单', pidUrl: '04baojiadan', objApi: 'b_offer_record' },
        { name: '合同', pidUrl: '05hetong', objApi: 'b_contract_info' },
        { name: '线索', pidUrl: '06xiansuo', objApi: 'b_leads' },
        { name: '产品', pidUrl: '07chanpin', objApi: 'b_product' },
        { name: '申请开票', pidUrl: '08shenqingkaipiao', objApi: 'b_invoice_info' },
        { name: '办公申请', pidUrl: '09bangongshenqing', objApi: 'c_approve_obj_data' }
      ],
      isVisibleSearchCus: false
    }
  },
  created() {
    this.getUserInfo()
    this.unreadSum()
    this.getLogoInfo()
    this.getOrgnizationList()
  },
  methods: {
    // resetForm() {
    //   this.$refs.ruleForm.resetFields()
    // },
    // 获取用户信息
    getUserInfo() {
      getUserInfo()
        .then((res) => {
          if (res.success) {
            this.userInfo = res.data
            this.userOrg = this.userInfo.belongOrganization
            this.$store.dispatch('setUserInfo', res.data)
            this.initAIChat()
            this.getQueryUserSecurity().then((res) => {
              if (res.data.openWatermark) {
                watermark.set(res.data.watermarkName, this.userInfo.realName)
              } else {
                watermark.set('', '')
              }
            })
            return queryFiles_api({ groupIds: !this.userInfo.headPortrait ? [] : [this.userInfo.headPortrait] })
          }
        })
        .then((res) => {
          this.avatorURL = ''
          if (res.success && res.data.length > 0) {
            this.avatorURL = res.data[0].url
          } else {
            if (this.userInfo.gender === 'gender_F') {
              this.avatorURL = require(`@/assets/images/user_avatar/miss_01.png`)
            } else {
              this.avatorURL = require(`@/assets/images/user_avatar/mr_01.png`)
            }
          }
        })
    },
    // 获取logo
    getLogoInfo() {
      getLogoInfo_api().then((res) => {
        if (res.success && res.data && res.data.url) {
          this.logo_url = res.data.url
        } else {
          this.logo_url = require('@/assets/logo.png')
        }
      })
    },
    // 获取组织
    getOrgnizationList() {
      getOrgnizationList().then((res) => {
        if (res.success) {
          this.orgnizations = res.data
        }
      })
    },
    changeOrg(val) {
      const userInfo = this.$store.state.userInfo
      userInfo.belongOrganization = val
      this.$store.dispatch('setUserInfo', userInfo)
    },
    // 退出登录
    onLogout() {
      setLogout().then((res) => {
        const { code } = res
        if (code !== 200) {
          return this.$message.error('退出失败')
        } else {
          sessionStorage.removeItem('webb_token')
          sessionStorage.removeItem('setRouterData')
          sessionStorage.removeItem('permissions')
          this.$store.commit('setRouterNot', true)
          this.$router.replace('/login')
        }
      })
    },

    /* 修改用户资料 start */
    // 关闭修改资料弹窗
    closeChangeDialog() {
      this.changeDataDialog = false
      this.getUserInfo()
    },
    /* 修改用户资料 end */

    /* 消息提醒 start */
    // 获取未读数量
    unreadSum() {
      unreadSum().then((res) => {
        if (res.success) {
          this.messageNum = res.data || 0
        }
      })
    },
    // 关闭消息提醒抽屉
    handleClose() {
      this.unreadSum()
      this.messageVisible = false
    },
    /* 消息提醒 end */

    /* 修改密码 start */
    // 获取用户密码修改规则
    queryUserSecurity() {
      queryUserSecurity_api().then((res) => {
        if (res.success) {
          this.userSecurity = res.data
          const { passwordComponent, passwordLength } = this.userSecurity
          const componentArr = passwordComponent.split(',')
          const msgArr = [123, '数字', '小写字母', '大写字母', '特殊字符(如"," "@"等)']
          this.str = ''
          for (let i = 0; i < componentArr.length; i++) {
            this.str += `${msgArr[componentArr[i]]}和`
          }
          this.str = `密码必须包含${this.str.slice(0, -1)}`
          this.str = `${this.str} 密码最短${passwordLength}位`
          this.changePsdDialog = true
        }
      })
    },
    // 修改密码
    openPsdDialog() {
      this.queryUserSecurity()
    },
    // 关闭修改密码弹窗
    closePsdDialog() {
      this.changePsdDialog = false
    },
    // 修改密码提交
    submitPassWord() {
      const { passwordLength, passwordComponent } = this.userSecurity
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.ruleForm.checkPass.length < passwordLength) {
            return this.$message.warning(`密码长度不能低于${passwordLength}位`)
          }
          updatePassword_api(this.ruleForm)
            .then((res) => {
              if (res.success) {
                this.sucPwdDialog = true
              }
            })
            .catch((err) => {
              if (err.code === 7001001) {
                this.$message.warning(err.message)
              } else {
                const componentArr = passwordComponent.split(',')
                const msgArr = [123, '数字', '小写字母', '大写字母', '特殊字符(如"," "@"等)']
                this.str = ''
                for (let i = 0; i < componentArr.length; i++) {
                  this.str += `${msgArr[componentArr[i]]}和`
                }
                this.str = '密码只能包含' + this.str.slice(0, -1)

                this.$message.warning(this.str)
              }
            })
        } else {
          return false
        }
      })
    },
    // 修改密码二次确认
    confirmPwd() {
      this.changePsdDialog = false
      sessionStorage.removeItem('webb_token')
      this.$router.push('/login')
    },
    // 修改密码重置弹窗
    psdOpen() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields()
        this.ruleForm = this.$options.data.call(this).ruleForm
      })
    },
    initAIChat() {
      getObtainCozeTokenApi().then((res) => {
        if (res.success) {
          const token = res.data //'czs_hnT4VQMXCyJ2zl3kvU0CGGe27KZJxkDYHRQAFSnqwTnwUjIcN5cjvKDwqyzRgqUGY'

          // 创建script标签
          const script = document.createElement('script')
          script.type = 'text/javascript'
          script.src = 'https://lf-cdn.coze.cn/obj/unpkg/flow-platform/chat-app-sdk/1.1.0-beta.0/libs/cn/index.js' // 普通JS脚本文件的路径
          script.onload = () => {
            new CozeWebSDK.WebChatClient({
              config: {
                bot_id: '7452215494088179724'
              },
              auth: {
                //鉴权方式，默认type 为unauth，表示不鉴权；建议设置为 token，表示通过PAT或OAuth鉴权
                type: 'token',
                //type 为 token 时，需要设置PAT或OAuth访问密钥
                token: token,
                //访问密钥过期时，使用的新密钥，可以按需设置。
                onRefreshToken: () => token
              },
              componentProps: {
                title: 'Coze'
              },
              userInfo: {
                id: this.userInfo.pid,
                url: 'https://lf-coze-web-cdn.coze.cn/obj/coze-web-cn/obric/coze/favicon.1970.png',
                nickname: this.userInfo.realName
              },
              ui: {
                chatBot: {
                  title: '瑞思德AI体检解读专家'
                },
                base: {
                  icon: 'https://rsd-shenghuoguan.oss-cn-wulanchabu.aliyuncs.com/%E6%B5%B7%E6%8A%A5-01.png',
                  layout: 'pc',
                  zIndex: 1000
                },
                footer: {
                  isShow: true,
                  expressionText: 'Powered by {{name}}',
                  linkvars: {
                    name: {
                      text: '瑞思德生物医学集团',
                      link: 'https://restorecn.cn/'
                    }
                  }
                }
              }
            })
          }
          // 将script标签添加到DOM中
          document.body.appendChild(script)
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/assets/css/public.scss';
@import '@/assets/css/list-style.scss';
.crmp-header {
  height: 100%;
  display: flex;
  padding: 0 20px;
  padding-left: 40px;
  justify-content: space-between;
  align-items: center;
  background: url('~@/assets/images/index/beijing@2x.png') no-repeat rgb(31, 67, 245);
  background-size: 100% 100%;
  .logo,
  .breadcrumb {
    height: 36px;
    line-height: 36px;
  }

  .logo {
    width: 180px;
    // background: url('~@/assets/logo.png') no-repeat left center;
    background-size: auto 100%;
    // background: $blue-color;
    color: #fff;
    text-align: left;
    img {
      height: 100%;
      width: auto;
    }
  }

  .breadcrumb {
    width: calc(100% - 240px);
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left {
      display: flex;
      align-items: center;
      visibility: hidden;
      .el-icon-s-home {
        font-size: 36px;
        color: $blue-color;
      }
    }

    .right {
      display: flex;
      align-items: center;
      .el-input {
        width: 200px;
        margin-right: 36px;
      }
      i {
        width: 32px;
        height: 32px;
        line-height: 32px;
        font-size: 14px;
        margin-left: 15px;
        color: $blue-color;
        background: #f4f7fd;
        text-align: center;
        border-radius: 50%;
        font-weight: bold;
        cursor: pointer;
      }

      .el-avatar {
        width: 32px;
        height: 32px;
        margin: 0 15px;
        ::v-deep img {
          width: 100%;
          height: auto;
        }
      }

      span {
        color: #444c5b;
        font-size: 18px;
        line-height: 32px;

        i {
          margin-right: 5px;
          background-color: #3a77fa;
          color: #fff;
        }
      }
    }
  }
}
.message-badge {
  width: 32px;
  height: 32px;
  margin-right: 26px;
  ::v-deep .is-fixed {
    right: -2px !important;
    border: none;
  }
}

.psd-form {
  .el-form-item {
    width: 100% !important;
    ::v-deep .el-form-item__content {
      display: flex;
      align-items: center;
      .el-input {
        width: 360px;
        margin-right: 10px;
      }
      // .el-form-item__error {
      //   position: absolute;
      //   top: 43% !important;
      //   transform: translateY(-50%);
      //   left: 390px;
      // }
    }
    .psd-txt {
      width: 200px;
      display: inline-block;
      line-height: 20px;
      color: #909399;
    }
  }
}
</style>
<style lang="scss">
.header-popper {
  width: auto;
  min-width: auto;

  .login-pop {
    display: flex;
    flex-flow: column;
    align-items: center;
    justify-content: center;

    .el-button {
      min-width: 100px;
      background-color: #3a77fa;
      border: 1px solid #3a77fa;
    }

    .el-button + .el-button {
      margin-left: 0;
      margin-top: 5px;
    }
    .org-btn {
      min-width: 100px;
      margin-top: 10px;
      border-radius: 4px;
      padding: 4px 10px;
      text-align: center;
      border: 1px solid transparent;
      cursor: pointer;
      &:first-child {
        margin-top: 0;
      }
      &:hover {
        background-color: rgba($color: #3a77fa, $alpha: 0.1);
      }
      &.active {
        color: #fff;
        background-color: #3a77fa;
        border-color: #3a77fa;
      }
    }
  }
}

.to-style {
  background-image: linear-gradient(to right, #ffebb5, #ffd783);
  border-radius: 5px;
  color: #7d5e39;
  font-size: 12px !important;
  padding: 5px;
  font-weight: 600;
}
.to-pop {
  width: 400px;
  display: flex;
  padding: 10px;
  flex-flow: row wrap;
  li {
    width: 20%;
    height: 80px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }
}
.orgStyle {
  display: inline-block;
  margin-right: -5px;
  .el-input {
    width: 300px !important;
  }
  .el-input__inner {
    width: 300px !important;
  }
  .el-input--suffix .el-input__inner {
    width: 300px !important;
  }
  .el-input__icon {
    height: 100%;
  }
}
</style>

<style>
.message-drawer .el-drawer__header {
  display: none;
}
</style>
